package com.system.servlet;

import com.ramostear.captcha.HappyCaptcha;
import com.system.dao.BaseDao;
import com.system.service.UserService.UserService;
import com.system.service.UserService.UserServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

public class RegisterServlet extends HttpServlet {
    /**
     * 这外面的都是配置上传的基本信息
     */
    private static final long serialVersionUID = 1L;
    //上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "upload";
    // 上传配置
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB
    String filePath = null;
    String fileName = null;
    /*********前端内容***********/
    String UserCode = null;
    String UserPsw = null;
    String rUserPsw = null;
    String code = null;//验证码
    boolean flag;
    /*********数据***********/
    /**
     * 提交带有文件的表带不能用doGet
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
    /**
     * 通过Post提交表单
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**************************检测是否为多媒体上传**************************/
        if(!ServletFileUpload.isMultipartContent(req)){
            //如果不是则停止
            PrintWriter writer = resp.getWriter();
            writer.println("Error:表单必须包含enctype=multipart。form-data");
            writer.flush();
            return;
        }
        /***************************设置上传文件********************************/
        //配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置内存临界值 - 超过后将产生零时文件并存储与临时目录中
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        //设置临时存储目录
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);

        //设施最大文件上传值
        upload.setFileSizeMax(MAX_FILE_SIZE);

        //设置最大请求值
        upload.setSizeMax(MAX_REQUEST_SIZE);

        //中文处理
        upload.setHeaderEncoding("UTF-8");

        //构造临时路径来存储上传的文件
        //这个路径相对当前应用的目录
        String uploadPath = req.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;

        //如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if(!uploadDir.exists()){
            uploadDir.mkdir();
        }
        try{
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(req);
            if(formItems != null && formItems.size() > 0){
                //矢代表单数据
                for(FileItem item : formItems){
                    if(item.isFormField()){
                        String name = item.getFieldName();//获取前端名字
                        String value = item.getString("UTF-8"); //获取输入内容
                        if(name.equals("UserCode")){
                            UserCode = value;
                        }
                        if(name.equals("UserPsw")){
                            UserPsw = value;
                        }
                        if(name.equals("code")){
                            code = value;
                        }
                        if(name.equals("rUserPsw")){
                            rUserPsw = value;
                        }

                        System.out.println(name + "=" + value);
                    }

                    //处理不在表单钟的字段
                    if(!item.isFormField()){
                        fileName = new File(item.getName()).getName();
                        System.out.println(fileName);

                        filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        //在控制台输出文件的上传路径
                        System.out.println(filePath);
                        //保存文件到硬盘
                        item.write(storeFile);
                        req.setAttribute("message","文件上传成功！");
                    }
                }
            }
        } catch (Exception e) {
            req.setAttribute("message","错误信息：" + e.getMessage());
            e.printStackTrace();
        }
        /*********这边需要处理图片名字***********/
        String uuid = UUID.randomUUID().toString();

        flag = HappyCaptcha.verification(req,code,true);
        /**********处理获取的数据************************/
        try {
            UserService userService = new UserServiceImpl();
            //判断是否为空
            if(UserCode.equals("") || UserPsw.equals("") || rUserPsw.equals("") || fileName.equals("")){
                String msg = "有未填入选项，请填写完整在提交";
                req.setAttribute("msg",msg);
                req.getRequestDispatcher("register.jsp").forward(req,resp);
            }
            //判断验证码是否正确
            else if(!flag) {
                String msg = "验证码错误";
                req.setAttribute("msg",msg);
                req.getRequestDispatcher("register.jsp").forward(req,resp);
            }
            //判断是否有相同的用户名
            else if(userService.IfRepetition(UserCode)){
                //有相同用户
                String msg = "该用户名已被人注册";
                req.setAttribute("msg",msg);
                req.getRequestDispatcher("register.jsp").forward(req,resp);
            }
            //两次密码验证是否一致
            else if(!UserPsw.equals(rUserPsw)){
                String msg = "两次密码不一致，请重新输入";
                req.setAttribute("msg",msg);
                req.getRequestDispatcher("register.jsp").forward(req,resp);
            }
            else{
                //保存数据到数据库，图片存放到规定位置
                fileName = uuid;
                userService.Register(UserCode,UserPsw,0,0,fileName);
                copyFile(filePath,"E:\\IDEA\\资源文件\\upload\\user\\"+fileName+".jpg"); //放到我们规定的文件地址
                //确认无误后重定向到登陆界面
                System.out.println("注册成功！");
                resp.sendRedirect("login.jsp");
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
//        req.getRequestDispatcher("login.jsp").forward(req,resp);
    }
    /********************将图片复制到项目中***********************/
    /**因为不能通过浏览器访问本机资源，所以通过复制文件的方式克服该困难***/
    public void copyFile(String oldPath, String newPath){
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ( (byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        }
        catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();
        }
    }
    public void InsertImage(String imageName) throws SQLException {
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        System.out.println(imageName+"文件拖入数据库。。");
        Connection connection = BaseDao.getConnection();
        if (connection!=null){
            System.out.println("执行成功");
            String sql = "insert into image(filename) values(?)";
            Object o[] = {imageName};
            BaseDao.excute(connection,preparedStatement,sql,o);
        }
        System.out.println("执行完成！");
    }
}
